package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RecursionMapper;
import com.zzyl.service.RecursionService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.zzyl.enums.BasicEnum.ENABLED_CANNOT_DELETED;

@Service
public class RecursionServiceImpl implements RecursionService {

    @Autowired
    private RecursionMapper recursionMapper;

    @Override
    public List<ResourceVo> list(ResourceDto resourceDto) {
        ResourceVo resourceVo = BeanUtil.toBean(resourceDto, ResourceVo.class);
        List<ResourceVo> list = recursionMapper.list(resourceVo);
        return list;
    }

    @Override
    public TreeVo tree(ResourceDto resourceDto) {
//        TreeVo treeVo = new TreeVo();
//
//        //1.先查出根资源（resource_no最小的）
//        Resource resource = recursionMapper.selectRootResource();
//
//        return treeVo;


        //查询所有菜单数据
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        resource.setResourceType("m");
        resource.setDataState("0");
        ResourceVo resourceVo = BeanUtil.toBean(resource, ResourceVo.class);
        List<ResourceVo> listResources = recursionMapper.list(resourceVo);
        //装所有数据
        List<TreeItemVo> treeItemVos = new ArrayList<>();
        //根目录
        ResourceVo root = new ResourceVo();
        root.setResourceNo("100001000000000");
        root.setResourceName("智慧养老院");
        //从一级以下开始递归
        recursionTree(treeItemVos, root, listResources);

        TreeVo treeVo = new TreeVo();
        treeVo.setItems(treeItemVos);
        return treeVo;
    }

    @Override
    public void insert(ResourceDto resourceDto) {
        //1.实体类类型转化
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);

        //2.查询父资源,并获取父资源状态
        String parentResourceNo = resourceDto.getParentResourceNo();
        Resource parentResource = recursionMapper.selectByParentNo(parentResourceNo);

        //3.将新建的资源状态，设置为父资源的状态
        resource.setDataState(parentResource.getDataState());

        //4.判断父资源是否已经是三级资源，如果是就不能新增资源
        if (NoProcessing.processString(parentResourceNo).length() / 3 >= 5){
            throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }

        //5.根据父资源的编号生成子资源的编号
        String resourceNo = createResourceNo(parentResourceNo);
        resource.setResourceNo(resourceNo);

        //6.根据信息新增
        recursionMapper.insert(resource);
    }



    @Override
    public void updateResource(ResourceDto resourceDto) {
        //转换实体类类型
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        recursionMapper.update(resource);
    }

    @Override
    public void setEnable(ResourceVo resourceVo) {
        //启用菜单
        if (resourceVo.getDataState().equals("0")) {
            //判断父资源是否是禁用
            //如果是禁用，不能启用
            String parentResourceNo = resourceVo.getParentResourceNo();
            Resource parentResource = recursionMapper.selectByResourceNo(parentResourceNo);
            if (parentResource != null && parentResource.getDataState().equals("1")) {
                throw new BaseException(BasicEnum.PARENT_MENU_DISABLE);
            }
        }

        //判断是否有子资源，如果有子资源，则一起启用或禁用
        String resourceNo = resourceVo.getResourceNo();
        recursionMapper.updateByResourceNo(resourceNo, resourceVo.getDataState());

        //传入父资源的resource_no的处理后格式（删掉多余的0）
        recursionMapper.updateByParentResourceNo(NoProcessing.processString(resourceNo), resourceVo.getDataState());
    }


    @Override
    public void deleteByResourceNo(String resourceNo) {
        if (childCount(resourceNo)) {
            throw new BaseException(BasicEnum.ENABLED_CANNOT_DELETED);
        }

        Resource resource = recursionMapper.selectByResourceNo(resourceNo);

        if(resource == null || resource.getDataState().equals('0')){
            throw new BaseException(BasicEnum.ENABLED_CANNOT_DELETED);
        }

        recursionMapper.deleteByResourceNo(resourceNo);
    }


    private void recursionTree(List<TreeItemVo> treeItemVos, ResourceVo root, List<ResourceVo> listResources) {
        //先构建根目录对象
        TreeItemVo itemVo = new TreeItemVo();
        itemVo.setId(root.getResourceNo());
        itemVo.setLabel(root.getResourceName());
        //构造根目录下的一级菜单
        List<ResourceVo> childlist = listResources
                .stream().
                filter(r -> r.getParentResourceNo().equals(root.getResourceNo())).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(childlist)) {
            //递归使用的子集对象
            List<TreeItemVo> children = new ArrayList<>();
            //递归的2级，3级数据
            childlist.forEach(res -> {
                recursionTree(children, res, listResources);
            });
            //设置子集child属性
            itemVo.setChildren(children);
        }
        //item 集合添加菜单对象
        treeItemVos.add(itemVo);
    }


    public String createResourceNo(String parentResourceNo){
        //1.根据父资源编号查询名下是否有子资源
        String max = recursionMapper.getMaxResourceNo(parentResourceNo);

        //2.没有子资源
        if(max == null){
            String resourceNo = NoProcessing.createNo(parentResourceNo, false);
            return resourceNo;
        }

        //3.有子资源
        String resourceNo = NoProcessing.createNo(max, true);
        return resourceNo;
    }


    //是否存在子资源
    private boolean childCount(String resourceNo) {
        int result = recursionMapper.childCount(resourceNo);
        if(result>0){
            return true;
        }
        return false;
    }

    //TODO happy

}